<?php
class SupplierController extends Zend_Controller_Action
{	
	public function init()
	{
		IndexController::initAdmin($this);
		$this->_arrKey	= array('id','name','weekday', 'leadtime','status' ,'order_frequency');
	}
	
	public function indexAction()
	{
		$intPage		= $this->_request->getParam('page', 1);
		$intLimit		= $this->_request->getParam('li', 50);
		$strSku			= $this->_request->getParam('sku', null);
		$strTotalSku			= $this->_request->getParam('total_sku', 11);
		$strSupplier	= $this->_request->getParam('supplier', null);
		
		$arrParams	= array
		(
			'sku'			=> trim($strSku),
			'total_sku'		=> trim($strTotalSku),
			'supplier'		=> trim($strSupplier)
		);

		$obj			= new QSupplier($this->AppUI->country);
		$intTotal		= $obj->totalPreparePO($arrParams);
		
		$arrSupplier =  $obj->search(1, 'all', null);
		
		$this->view->arrSupplier = $arrSupplier;
		
		if($intTotal)
		{
			$intOffset	= ($intPage-1)*$intLimit;
			$arrResult	= $obj->getPreparePO($intOffset, $intLimit, $arrParams);
			
			$arrTitle	= array();
			foreach($arrResult as $data)
			{
				foreach($data as $key=>$value){
					$arrTitle[]	= $key;
				}
				break;
			}
			
			$intTotalPage = ceil($intTotal/$intLimit);
			$this->view->intTotalPage = $intTotalPage;
			if ($intTotalPage>1)
			{
				$strQuery = null;
				if ($strSku){ $strQuery.= '&sku='.$strSku; }
				if ($strSupplier){ $strQuery.= '&supplier='.$strSupplier; }
				$objPaginator = new Common_Paginator($intTotalPage, $intPage);
				$objPaginator->setUrl(HOST_ADMIN.'/supplier');
				$objPaginator->setQuery($strQuery);
				$this->view->strPaginator = $objPaginator->showAdmin();
			}
			
			$this->view->arrResult = $arrResult;
			$this->view->arrTitle = $arrTitle;
		}	
		$this->view->intTotal		= $intTotal;
		$this->view->strSku			= $strSku;
		$this->view->strTotalSku			= $strTotalSku;
		$this->view->strSupplier	= $strSupplier;
		$this->view->arrLogisticType = CConfig::$LogisticType;
		$this->view->arrLogisticMethod = CConfig::$LogisticMethod;
		$this->view->arrLogisticEta = CConfig::$LogisticEta;
	}
	
	public function exportAction()
	{
		set_time_limit(9999);
		
		$strSku			= $this->_request->getParam('sku', null);
		$strSupplier	= $this->_request->getParam('supplier', null);
		
		$arrParams	= array
		(
			'sku'		=> trim($strSku),
			'supplier'	=> trim($strSupplier)
		);
					
		$arrCategory	= $this->AppUI->admin_category ? explode(';', $this->AppUI->admin_category) : null;
		if(!$arrCategory && $this->AppUI->admin_group_id!=GROUP_Administrator){
			$arrCategory= array('xyz');
		}
		
		$obj		= new QSupplier($this->AppUI->country);
		$arrParams	= array();
		$arrResult	= $obj->getPrepareExportPO(0, 'all', $arrParams); 
	
		if($arrResult)
		{
			$arrTitle	= array();
			foreach($arrResult as $data)
			{
				foreach($data as $key=>$value){
					$arrTitle[]	=  $key;
				}
				break;
			}
			
			$strFname	= 'po_data.'.date('YmdHis').'.csv';
			$strCSV		= null;
			$strCSV		= $strCSV. implode(';', $arrTitle)."\r\n";
			foreach($arrResult as $data)
			{
				$arrRecord		= array();
				foreach($data as $key=>$value)
				{
						$arrRecord[]	= $value;
				}
				$strCSV	= $strCSV. implode(';', $arrRecord)."\r\n";
			}
			$strCSV = chr(255).chr(254).mb_convert_encoding($strCSV, "UTF-16LE", "UTF-8");	
			header("Content-type: application/ms-excel");
			header("Content-disposition: attachment; filename=".$strFname."; size=".strlen($strCSV));
			header('Cache-Control: max-age=0'); 
			echo $strCSV;
		}
		exit;
	}
	
	public function calendarAction()
	{
		$intPage		= $this->_request->getParam('page', 1);
		$intLimit		= $this->_request->getParam('li', 50);
		$strName		= $this->_request->getParam('name', null);
		$strWeekday		= $this->_request->getParam('weekday', null);
		$strOrderField	= $this->_request->getParam('orf', 'name');
		$strOrderValue	= $this->_request->getParam('orv', 'asc');
		
		$arrParams	= array
			(
				'name'		=> trim($strName),
				'weekday'		=> trim($strWeekday),
				'orf'		=> trim($strOrderField),
				'orv'		=> trim($strOrderValue)
				);
		
		#Category
		$objCategory	= new CCategory($this->AppUI->country);
		$arrData		= $objCategory->get();
		$arrCategoryData= isset($arrData['category']) ? $arrData['category'] : null;
		$arrCategory	= array();
		
		$obj			= new QSupplier($this->AppUI->country);
		$intTotal		= $obj->total($arrParams);
		
		if($intTotal)
		{
			$intOffset	= ($intPage-1)*$intLimit;
			$arrResult	= $obj->search($intOffset, $intLimit, $arrParams);
			
			$arrTitle	= array();
			foreach($arrResult as $data)
			{
				foreach($data as $key=>$value){
					$arrTitle[]	= $key;
				}
				break;
			}
		
			$intTotalPage = ceil($intTotal/$intLimit);
			$this->view->intTotalPage = $intTotalPage;
			if ($intTotalPage>1)
			{
				$strQuery = null;
				if ($strName){ $strQuery.= '&name='.$strName; }
				if ($strWeekday){ $strQuery.= '&weekday='.$strWeekday; }
				if ($strOrderValue){ $strQuery.= '&orv='.$strOrderValue; }
				if ($strOrderValue){ $strQuery.= '&orv='.$strOrderValue; }
				$objPaginator = new Common_Paginator($intTotalPage, $intPage);
				$objPaginator->setUrl(HOST_ADMIN.'/supplier/calendar');
				$objPaginator->setQuery($strQuery);
				$this->view->strPaginator = $objPaginator->showAdmin();
			}
		
			$this->view->arrTitle	= $arrTitle;
			$this->view->arrResult	= $arrResult;
		}	
		$this->view->intTotal		= $intTotal;
		$this->view->strName		= $strName;
		$this->view->strWeekday		= $strWeekday;
		$this->view->strOrderField	= $strOrderField;
		$this->view->strOrderValue	= $strOrderValue;
	}
	
	public function calendarExportAction()
	{
		set_time_limit(9999);
		
		$strName		= $this->_request->getParam('name', null);
		$strWeekday		= $this->_request->getParam('weekday', null);
		$strOrderField	= $this->_request->getParam('orf', 'name');
		$strOrderValue	= $this->_request->getParam('orv', 'asc');
		
		$arrParams	= array
			(
				'name'		=> trim($strName),
				'weekday'	=> trim($strWeekday),
				'orf'		=> trim($strOrderField),
				'orv'		=> trim($strOrderValue)
				);
		
		#Category
		$objCategory	= new CCategory($this->AppUI->country);
		$arrData		= $objCategory->get();
		$arrCategoryData= isset($arrData['category']) ? $arrData['category'] : null;
		$arrCategory	= array();
		
		$obj			= new QSupplier($this->AppUI->country);
		$intTotal		= $obj->total($arrParams);
		
		if($intTotal)
		{
			$arrResult	= $obj->search(0, 'all', $arrParams);
			
			$arrTitle	= array();
			foreach($arrResult as $data)
			{
				foreach($data as $key=>$value){
					$arrTitle[]	= $key;
				}
				break;
			}
			
			$strFname	= 'supplier-calendar.'.date('YmdHis').'.csv';
			$strCSV		= null;
			$strCSV		= $strCSV. implode(';', $arrTitle)."\r\n";
			foreach($arrResult as $data)
			{
				$arrRecord		= array();
				foreach($data as $key=>$value)
				{
					$arrRecord[]	= $value;
				}
				$strCSV	= $strCSV. implode(';', $arrRecord)."\r\n";
			}
			$strCSV = chr(255).chr(254).mb_convert_encoding($strCSV, "UTF-16LE", "UTF-8");	
			header("Content-type: application/ms-excel");
			header("Content-disposition: attachment; filename=".$strFname."; size=".strlen($strCSV));
			header('Cache-Control: max-age=0'); 
			echo $strCSV;
		}
		exit;
	}
	
	public function updateFieldAction()
	{
		if($this->_request->isPost())
		{
			$strField		= $this->_request->getParam('f', null);
			$mixValue		= $this->_request->getParam('v', 0);
			$id				= $this->_request->getParam('id', 0);
			if($strField)
			{
				$obj		= new QSupplier($this->AppUI->country);
				$arrParams	= array(	'id' => $id ,
										$strField=>$mixValue
									);
				$obj->updateField($arrParams);
				echo json_encode(array('result'=>1));
			}
		}
		exit;
	}
	
	#Sale Data
	public function saveAction()
	{
		$objFile	= isset($_FILES['file']) ? $_FILES['file'] : null ;
		if(!$objFile['name'])
		{
			//echo '<script>parent.show_error("saledata", "null")</script>';
			exit;
		}
		if($objFile)
		{
			$strDelimiter	= ",";
			
			$arrKey			= $this->_arrKey;
			$db				= Zend_Registry::get('db');
			$strQuery		= "TRUNCATE TABLE ". $this->AppUI->country . "_tmp_suppliers; 
								LOAD DATA LOCAL INFILE '".str_replace('\\', '/', $objFile['tmp_name'])."' 
								INTO TABLE " . $this->AppUI->country . "_tmp_suppliers 
								FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
								LINES TERMINATED BY '\r\n'
								IGNORE 1 LINES (".implode(',', $arrKey).")";
			$db		= Zend_Registry::get('db');
			$db->execute($strQuery);

			$strQuery ="Update " . $this->AppUI->country . "_suppliers s inner join " . $this->AppUI->country ."_tmp_suppliers t on s.id =t.id ".
			            "Set s.weekday = t.weekday, s.leadtime = t.leadtime, s.order_frequency = t.order_frequency ; ";
						
			$db->execute($strQuery);
			$db->closeConnection();
			
			echo '<script>parent.update_done();</script>';
			exit;
		}
		exit;
	}
	
	public function popupAction()
	{
		$intPage		= $this->_request->getParam('page', 1);
		$intLimit		= $this->_request->getParam('li', 16);
		$strSupplierId		= $this->_request->getParam('supplierId', 0);
		
		$obj			= new QSupplier($this->AppUI->country);		
		$arrSupplier =  $obj->search(1, 'all', null);
		
		$objPoDetail = new QPoDetail($this->AppUI->country);		
		$intTotal	= $objPoDetail->getTotalBySupplier($strSupplierId);
		$arrResult =array();
		if($intTotal)
		{
			$intOffset	= ($intPage-1) * $intLimit;
			$arrResult = $objPoDetail->getbySupplier($intOffset, $intLimit, $strSupplierId);		
		}
		
		$intTotalPage = ceil($intTotal/$intLimit);

		$arrPaging  =array();
		for($i =1 ; $i <= $intTotalPage; $i++)
		{
		  	$arrPaging[$i] = $i;
		}	
		
		$arrTitle	= array();
		foreach($arrResult as $data)
		{
			foreach($data as $key=>$value){
				$arrTitle[]	= $key;
			}
			break;
		}
		$this->view->arrResult = $arrResult;
		$this->view->arrTitle = $arrTitle;
		$this->view->arrPaging = $arrPaging;
		$this->view->intTotalPage = $intTotalPage;
		$this->view->supplierId = $strSupplierId;
		$this->view->intPage = $intPage;
		$this->view->intTotal =$intTotal;
		$this->view->intLimit = $intLimit;
		$this->view->arrSupplier = $arrSupplier;
	}
	
	public function infoAction()
	{
		$intPage		= $this->_request->getParam('page', 1);
		$intLimit		= $this->_request->getParam('li', 16);
		$strSupplierId		= $this->_request->getParam('supplierId', 0);
		
		$obj			= new QSupplier($this->AppUI->country);		
		$arrSupplier =  $obj->search(1, 'all', null);
		
		$objPoDetail = new QPoDetail($this->AppUI->country);		
		$intTotal	= $objPoDetail->getTotalBySupplier($strSupplierId);
		$arrResult =array();
		if($intTotal)
		{
			$intOffset	= ($intPage-1) * $intLimit;
			$arrResult = $objPoDetail->getbySupplier($intOffset, $intLimit, $strSupplierId);		
		}
		
		$intTotalPage = ceil($intTotal/$intLimit);

		$arrPaging  =array();
		for($i =1 ; $i <= $intTotalPage; $i++)
		{
			$arrPaging[$i] = $i;
		}	
		
		$arrTitle	= array();
		foreach($arrResult as $data)
		{
			foreach($data as $key=>$value){
				$arrTitle[]	= $key;
			}
			break;
		}
		$this->view->arrResult = $arrResult;
		$this->view->arrTitle = $arrTitle;
		$this->view->arrPaging = $arrPaging;
		$this->view->intTotalPage = $intTotalPage;
		$this->view->supplierId = $strSupplierId;
		$this->view->intPage = $intPage;
		$this->view->intTotal =$intTotal;
		$this->view->intLimit = $intLimit;
		$this->view->arrSupplier = $arrSupplier;
	}
	
	public function deleteDetailAction()
	{
		$id		= $this->_request->getParam('id', 0);
		$objPoDetail = new QPoDetail($this->AppUI->country);
		$objPoDetail->deletebyId($id); 
		
		exit;
	}
	
	public function saveDetailAction()
	{
		$id					= $this->_request->getParam('id', 0);
		$cost_item			= $this->_request->getParam('cost_item', 0);
		$quantity			= $this->_request->getParam('quantity', 0);
		$item_tax_amount	= $this->_request->getParam('item_tax_amount', 0);
		$supplier_id		= $this->_request->getParam('supplier_id', 0);
		
		//update po detail
		$arrParam =array(
			'id'				=> $id,
			'cost_item'			=> $cost_item,
			'quantity'			=> $quantity,
			'item_tax_amount'	=> $item_tax_amount==''?0: $item_tax_amount,
			'supplier_id'		=> $supplier_id
			);
		$objPoDetail = new QPoDetail($this->AppUI->country);
		$objPoDetail->update($arrParam);
		
		//create POHeader if supplier no PO
		$objPoHeader = new QPoHeader($this->AppUI->country);
		$arrData = $objPoHeader->getbySupplierId($supplier_id);
		if(!$arrData)
		{
			$arrData = $objPoHeader->getlastPONumber();
			$secondPhrase =  intval(substr($arrData[0]['po_number'] , -4)) + 1;
			$firstPhrase =  substr($arrData[0]['po_number'] ,0 , 11);
			$arrInsert = array(
						'supplier_id' =>  $supplier_id,
				'po_number'	  =>  $firstPhrase . substr('0000' .  (string) $secondPhrase, -4)	
						);	
			$objPoHeader->insert($arrInsert);
		}
		exit;
	}
	
	public function saveHeaderAction()
	{
		$id					= $this->_request->getParam('id', 0);
		$logistic_type		= $this->_request->getParam('logistic_type', '');
		$logistic_method	= $this->_request->getParam('logistic_method', '');
		$logistic_date		= $this->_request->getParam('logistic_date', '');
		$logistic_eta		= $this->_request->getParam('logistic_eta', '');
		
		//update po detail
		$arrParam = array(
			'id'					=> $id,
			'logistic_type'			=> $logistic_type,
			'logistic_method'		=> $logistic_method,
			'logistic_date'			=> $logistic_date==''?null: $logistic_date,
			'logistic_eta'			=> $logistic_eta
			);
		
		//Update POHeader if supplier no PO
		$objPoHeader = new QPoHeader($this->AppUI->country);
		$objPoHeader->update($arrParam);

		exit;
	}
}
?>
